package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author alexis
 * @date 2025-05-26
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private CheckInConfigServiceImpl checkInConfigServiceImpl;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    /**
     * 入住申请
     * @param checkInApplyDto
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto checkInApplyDto) {
        //1.检验老人是否已入住 -是-老人已入住  --否
        LambdaQueryWrapper<Elder> elqw = new LambdaQueryWrapper<>();
        elqw.eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(elqw); //获取老人信息
        if (ObjectUtil.isNotEmpty(elder)) {
            throw new BaseException("该老人已入住！");
        }

        //2.更新床位状态为已入住
      /*  Bed bed = new Bed();
        bed.setId(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed); //使用MP中的updateById方法,传入的参数为实体类,实体类中包含主键id*/
        Long bedId = checkInApplyDto.getCheckInConfigDto().getBedId();
        Bed bed = bedMapper.selectById(bedId); // ✅ 从数据库中查询床位信息
        if (bed == null) {
            throw new BaseException("床位不存在");
        }
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //3.新增或更新老人
        elder = insertOrUpdateElder(checkInApplyDto.getCheckInElderDto(), bed);
        //4.新增签约信息
        saveContract(checkInApplyDto, elder);
        //5.新增入住信息
        CheckIn checkIn = saveCheckIn(checkInApplyDto, elder, bed);
        //6.新增入住配置
        saveCheckInConfig(checkInApplyDto.getCheckInConfigDto(), checkIn);


    }

    /**
     * 新增或更新老人信息
     * @param checkInElderDto
     * @param bed
     * @return
     */
    private Elder insertOrUpdateElder(CheckInElderDto checkInElderDto, Bed bed) {
        //1.封装老人数据
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        //2.查询老人是否存在，根据身份证号和状态
        LambdaQueryWrapper<Elder> elqw = new LambdaQueryWrapper<>();
        elqw.eq(Elder::getIdCardNo, elder.getIdCardNo())
                .eq(Elder::getStatus, 1);
        Elder elderDb = elderMapper.selectOne(elqw);
        if (ObjectUtil.isNotEmpty(elderDb)) {
            //存在--更新
            elder.setId(elderDb.getId());
            elderMapper.updateById(elder);
        } else {
            //不存在---新增
            elderMapper.insert(elder);
        }

        return elder;


    }

    /**
     * 保存签约信息
     * @param checkInApplyDto
     * @param elder
     */
    private void saveContract(CheckInApplyDto checkInApplyDto, Elder elder) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);

        //1.封装老人数据 id, name
        contract.setElderId(elder.getId().intValue());
        contract.setElderName(elder.getName());

        //2.获取开始时间和结束时间
        LocalDateTime startDate = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = checkInApplyDto.getCheckInConfigDto().getEndDate();
        //放进Contract对象
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        //3.设置状态 合同生效状态：当前时间>开始时间
        if (startDate.isBefore(LocalDateTime.now())) {
            contract.setStatus(1);
        }

        //4.设置合同编号
        String contractNumber = "HT" + CodeGenerator.generateContractNumber();
        contract.setContractNumber(contractNumber);

        contractMapper.insert(contract);

    }

    /**
     * 保存入住信息
     * @param checkInApplyDto
     * @param elder
     * @param bed
     * @return
     */
    private CheckIn saveCheckIn(CheckInApplyDto checkInApplyDto, Elder elder, Bed bed) {
        CheckIn checkIn = new CheckIn();
        //设置老人信息
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        //设置入住信息
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        //设置床位信息
        checkIn.setBedNumber(bed.getBedNumber()); //床位编号
        //设置家属信息
        List<ElderFamilyDto> elderFamilyDtoList = checkInApplyDto.getElderFamilyDtoList();
        //放到remark备注
        checkIn.setRemark(JSON.toJSONString(elderFamilyDtoList));

        //保存入住信息
        save(checkIn);
        return checkIn;
    }

    /**
     * 保存入住配置信息
     * @param checkInConfigDto
     * @param checkIn
     */
    private void saveCheckInConfig(CheckInConfigDto checkInConfigDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto, checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());

        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 入住详情
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        //创建结果对象
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //设置入住配置
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        CheckIn checkIn = checkInMapper.selectById(id);
        BeanUtils.copyProperties(checkIn, checkInConfigVo);

        //1.设置入住配置信息
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(new LambdaQueryWrapper<CheckInConfig>().eq(CheckInConfig::getCheckInId, id));
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);

        //2.设置老人信息
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        Long elderId = checkIn.getElderId();
        Elder elder = elderMapper.selectById(elderId);
        BeanUtils.copyProperties(elder, checkInElderVo);
        //获取老人年龄
        checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));
        checkInDetailVo.setCheckInElderVo(checkInElderVo); //设置老人信息

        // 3.设置家属响应信息
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(remark, ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVos);

        // 4.设置签约办理响应信息
        Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(Contract::getElderId, elderId));
        checkInDetailVo.setContract(contract);

        // 5.返回结果
        return checkInDetailVo;

    }
}
